﻿#include "NewPrjDialog.h"
#include "ui_NewPrjDialog.h"
#include "stores/DataStroes.h"
#include "utils/String/FileNameValidator.h"
#include "components/Toast/Toast.h"
#include "components/SingleInstanceApplication/SingleInstanceApplication.h"

#include <QFileDialog>
#include "components/FWidgets/FMessageBox/FMessageBox.h"
#include <QDebug>

NewPrjDialog::NewPrjDialog(QWidget *parent, Behavior behavior)
    : FDialog(parent)
    , ui(new Ui::NewPrjDialog)
    , m_behavior(behavior)
{
    ui->setupUi(this);

    switch (m_behavior) {
    case Create:
        setWindowTitle(tr("New Project"));
        break;
    case SaveAs:
        setWindowTitle(tr("Save Project As..."));
        break;
    }


    TlvProject* prj = DataStroes::instance()->tlvPrj();

    ui->lePrjName->setText(prj->model().data().name);
    ui->lePrjPath->setText(prj->latestProject());
}

NewPrjDialog::~NewPrjDialog()
{
    delete ui;
}

void NewPrjDialog::on_btnBrowse_clicked()
{
    QString savePath = QFileDialog::getSaveFileName(this, tr("Select save path"), ui->lePrjPath->text(), tr("Tlv Project File (*%1)").arg(TLVPRJ_EXT));
    if (savePath.isEmpty()) return;
    ui->lePrjPath->setText(savePath);
}

void NewPrjDialog::on_btnConfirm_clicked()
{
    QString prjName = ui->lePrjName->text();
    QString prjPath = ui->lePrjPath->text();

    TlvProject* prj = DataStroes::instance()->tlvPrj();
    switch (m_behavior) {
    case Create:
        prj->create(prjPath, prjName);
        Toast::success(tr("Create Successfully!\n") + prjPath);
        break;
    case SaveAs:
        prj->saveAs(prjPath, prjName);
        Toast::success(tr("Save As Successfully!\n") + prjPath);
        break;
    }
    if (FMessageBox::Yes == FMessageBox::question(this, tr("Question"), tr("Open new project now?"))) {
        qApp->restart(QStringList() << prjPath);
    }
    accept();
}

void NewPrjDialog::on_btnCancel_clicked()
{
    reject();
}
